<?php


namespace app\admin\controller;


use think\Db;

class Friend
{
        public function insert_Friend(){
            $fromid=$_POST['fromid'];
            $fromName=$_POST['fromName'];
            $toid=$_POST['toid'];
            $toName=$_POST['toName'];

            //查询friend表中是否有相同的记录有则 不作操作
            $res_1=Db::table("friend")->where("fromid",$fromid)->where("toid",$toid)->find();
            if($res_1 != null){
                $res=array("state"=>200,"type"=>"areadyhave");
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
                return ;
            }

            $res_2=Db::table("friend")->where("fromid",$toid)->where("toid",$fromid)->find();
            if($res_2 != null){
                $res=array("state"=>200,"type"=>"areadyhave");
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
                return ;
            }

            $data_1=array("fromid"=>$fromid,"fromName"=>$fromName,"toid"=>$toid,"toName"=>$toName);
            $data_2=array("fromid"=>$toid,"fromName"=>$toName,"toid"=>$fromid,"toName"=>$fromName);
            $effect_row_1=Db::table("friend")->insert($data_1);
            $effect_row_2=Db::table("friend")->insert($data_2);
            if(($effect_row_1 == 1) && ($effect_row_2 == 1)){
                $res=array("state"=>200,"type"=>"success","notify_to"=>$toid);
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
            }else{
                $res=array("state"=>400,"type"=>"fail");
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
            }
        }

        public function select_Friend(){
            $fromid=$_POST['fromid'];
            $res_arr=Db::table("friend")->where("fromid",$fromid)->select();
            if($res_arr != []){
                echo json_encode($res_arr,JSON_UNESCAPED_UNICODE);
            }else{
                $res=[];
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
            }
        }

        public function delete_Friend(){
            $fromid=$_POST['fromid'];
            $toid=$_POST['toid'];
            $res_1=Db::table("friend")->where("fromid",$fromid)->where("toid",$toid)->find();
            $res_2=Db::table("friend")->where("fromid",$toid)->where("toid",$fromid)->find();
            if(($res_1 == null) || ($res_2 == null)){
                $delete_friend=array("state"=>400,"type"=>"fail");
                echo json_encode($delete_friend,JSON_UNESCAPED_UNICODE);
                return ;
            }else{
                $res_3=Db::table("friend")->where("fromid",$fromid)->where("toid",$toid)->delete();
                $res_4=Db::table("friend")->where("fromid",$toid)->where("toid",$fromid)->delete();
                if($res_3 && $res_4){
                    $delete_friend=array("state"=>200,"type"=>"success");
                    echo json_encode($delete_friend,JSON_UNESCAPED_UNICODE);
                    return ;
                }
            }
        }
}